<template>
  <div class="box">
    <div class="scroll-view">
      <div class="user-title-box">{{ dataObj.node_name }}</div>
      <el-form :model="jdysRuleForm" :rules="jdysRules" ref="jdysRuleForm" label-width="80px" label-position="top">
        <div class="node-box" v-for="(item, index) in jdysFormList" :key="index">
          <!-- 文本 -->
          <el-form-item :label="`${item.name}${item.supervision_acceptance_status == 2 ? '（已通过）' : ''}`"
            :prop="item.prop" v-if="item.content_type == 1">
            <el-input class="textarea-input" :disabled="item.supervision_acceptance_status == 2" :rows="4"
              v-model="jdysRuleForm[item.prop].value" type="textarea"></el-input>
          </el-form-item>
          <!-- 图片，视频 -->
          <el-form-item :label="`${item.name}${item.supervision_acceptance_status == 2 ? '（已通过）' : ''}`"
            :prop="item.prop" v-else>
            <div class="file-list-box">
              <el-upload :disabled="item.supervision_acceptance_status == 2" multiple class="avatar-uploader"
                accept="image/*" action="#" :show-file-list="false" :auto-upload="false" list-type="picture-card"
                :on-change="(file, fileList) => {
                  jdysFileChange(file, fileList, item.prop);
                }
                  ">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <div class="file-item-box" v-for="(img, imgIndex) in jdysRuleForm[item.prop].value" :key="imgIndex">
                <div class="el-icon-delete-box" @click="jdysFileRemove(imgIndex, item.prop)"
                  v-if="item.supervision_acceptance_status != 2">
                  <i class="el-icon-error"></i>
                </div>
                <el-tooltip class="item" effect="dark" :content="img.name || img.file_name" placement="top">
                  <img class="img" :src="$fileImgFunc(img)" />
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
          <p v-if="item.reason_rejection" class="reason-rejection">审批意见：{{ item.reason_rejection }}</p>
        </div>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input :rows="4" class="input-box" v-model="jdysRuleForm.remark" type="textarea"></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="jdysSubmit('jdysRuleForm')" :disabled="diaLoading"
          :loading="diaLoading">提交</el-button>
        <el-button @click="jdysCancel('jdysRuleForm')">关闭</el-button>
      </span>
    </div>
  </div>
</template>
<script>
import engineeringApi from "@/api/engineeringApi";
import projectApi from "@/api/projectApi";

export default {
  name: "jdysCom",
  data() {
    return {
      jdysVisible: false,
      diaLoading: false,
      jdysRules: {},
      jdysRuleForm: {},
      jdysFormList: [],
      projectNodesItem: "",
      dataObj: ''
    };
  },
  watch: {},
  computed: {},
  mounted() {
    this.qualityAcceptanceDetails();
  },
  methods: {
    jdysCancel() {
      this.$goBackTab(this);
    },
    jdysFileChange(file, list, type) {
      let jdysRuleForm = this.jdysRuleForm;
      jdysRuleForm[type].value = list;
      this.jdysRuleForm = jdysRuleForm;
    },
    jdysFileRemove(index, type) {
      let jdysRuleForm = this.jdysRuleForm;
      jdysRuleForm[type].value.splice(index, 1);
      this.jdysRuleForm = jdysRuleForm;
    },
    jdysSubmit(formName) {
      let jdysRuleForm = this.jdysRuleForm;
      let projectNodesItem = this.projectNodesItem;
      console.log(jdysRuleForm, "节点验收参数", projectNodesItem);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.diaLoading = true;
          let formdata = new FormData();
          let obj = {
            project_id: this.dataObj.project_id,
            node_id: this.$route.query.id,
          };
          projectNodesItem.forEach((item) => {
            // 已通过不再次提交(文本)
            if (item.supervision_acceptance_status != 2) {
              let key = `name_${item.id}`;
              obj[key] = item.node_name;
            }
          });
          for (let i in jdysRuleForm) {
            // 已通过不再次提交
            if (jdysRuleForm[i].supervision_acceptance_status != 2) {
              if (typeof jdysRuleForm[i].value == "string") {
                // 文本
                obj[i] = jdysRuleForm[i].value;
              } else {
                // 文件
                jdysRuleForm[i].value.forEach((item) => {
                  // 是否存在文件
                  if (item.raw) {
                    formdata.append(`${i}[]`, item.raw);
                  }
                });
              }
            }
          }
          obj.remark = '';//描述默认为空
          formdata.append("data", JSON.stringify(obj));
          projectApi
            .nodeAcceptance(formdata)
            .then((res) => {
              console.log(res, "节点验收");
              this.diaLoading = false;
              if (res.code == 200) {
                this.jdysCancel();
              }
              this.$message({
                type: res.code == 200 ? "success" : "warning",
                message: res.code == 200 ? "处理成功" : res.message,
              });
            })
            .catch((err) => {
              this.diaLoading = false;
              this.$message({
                type: "warning",
                message: err.message,
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 节点验收（表单处理）
    jdysShouwFunc() {
      let projectNodesItem = this.projectNodesItem;
      console.log("节点", projectNodesItem);
      let jdysRuleForm = {};
      let jdysFormList = [];
      let jdysRules = {};

      projectNodesItem.forEach((item) => {
        let formName = "";
        let obj = {
          name: item.node_name,
          is_required: item.is_required,
          content_type: item.content_type,
          reason_rejection: item.reason_rejection,
        };
        if (item.content_type == 1) {
          // 文本
          formName = `content_${item.id}`;
          jdysRuleForm[formName] = {};//验收初始对象数据
          jdysRuleForm[formName].supervision_acceptance_status = item.supervision_acceptance_status;
          jdysRuleForm[formName].value = item.supervision_acceptance_status == 2 ? item.content : '';
        } else {
          // 图片视频
          formName = `file_${item.id}`;
          jdysRuleForm[formName] = {};//验收初始对象数据
          jdysRuleForm[formName].supervision_acceptance_status = item.supervision_acceptance_status;
          jdysRuleForm[formName].value = item.supervision_acceptance_status == 2 ? item.node_files : [];
        }
        obj.prop = formName;
        // 通过无需再次提交supervision_acceptance_status
        obj.supervision_acceptance_status = item.supervision_acceptance_status;
        if (item.is_required == 1 && item.supervision_acceptance_status != 2) {
          if (item.content_type == 1) {
            // 文本
            jdysRules[formName] = {
              required: true,
              validator: this.ysjdTxt,
              trigger: "change",
            };
            // [
            //   { required: true, message: "请输入内容", trigger: "change" },
            // ];
          } else {
            // 文件
            jdysRules[formName] = {
              required: true,
              validator: this.ysjdFile,
              trigger: "change",
            };
          }
        }
        jdysFormList.push(obj);
      });
      this.jdysFormList = jdysFormList; //formitem
      this.jdysRuleForm = jdysRuleForm; //填写数据
      this.jdysRules = jdysRules; //验证是否必填
      this.$nextTick(() => {
        this.jdysVisible = true;
      });
    },
    ysjdFile(rule, value, callback) {
      if (!value.value.length) {
        callback(new Error("请上传文件"));
      } else {
        callback();
      }
    },
    ysjdTxt(rule, value, callback) {
      if (!value.value) {
        callback(new Error("请填写内容"));
      } else {
        callback();
      }
    },
    // 详情
    qualityAcceptanceDetails() {
      return new Promise((resolve, reject) => {
        engineeringApi
          .qualityAcceptanceDetails({
            node_id: this.$route.query.id,
          })
          .then((res) => {
            console.log(res, "节点详情");
            if (res.code == 200) {
              // 判断当前需要验收的节点
              this.projectNodesItem = res.data.criteria_list;
              this.dataObj = res.data;
              this.$nextTick(() => {
                this.jdysShouwFunc();
              });
            } else {
              this.$message.warning(res.message);
            }
          })
          .catch((err) => {
            this.$message.warning(err.message);
          });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import './index.scss';
@import "@/styles/projectOparet.scss";
</style>